package where2go.sctu.com.zhiyou.utils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * ProjectName: zhiyou
 * PackageName: where2go.sctu.com.zhiyou.utils
 * Created by 张某人
 * CreatedTime:on 2018/5/26   18:12
 * Description:  重写StringRequest,添加请求头的请求
 */

public class HeaderStringRequest extends StringRequest {

    public static String JSESSIONID = null;

    //声明带有method请求类型的构造方法，方便使用post方法
    public HeaderStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
    }

    //默认使用get方式的构造的方法
    public HeaderStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(url, listener, errorListener);
    }

    //重写父类的 方法
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();
        //如果服务器传来的header无内容（就是没有消息头）
        if (headers == null || headers.equals(Collections.<String, String>emptyMap())) {
            headers = new HashMap<String, String>();
        }
        if (JSESSIONID != null) {
            headers.put("Cookie", JSESSIONID);
        }
        return headers;
    }

    /**
     * 此处重写StringRequest中的parseworkReseponse方法
     * 获取服务端传送至客户端的jsessionId
     *
     * @param response
     * @return
     */
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {

        Map<String, String> headers = response.headers;
        String sessionid = headers.get("Set-Cookie");
        if (sessionid != null) {
            JSESSIONID = sessionid.split(";")[0];
        }
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }
}
